﻿Imports System.Collections.ObjectModel
Imports System.Data
Imports System.Linq
Imports System.Text
Imports System.IO

Public Class CAPICContingenciaServicio

    Private dtInstrumentos As New DataTable
    Private dtPortafolios As New DataTable
    Private servGrales As New CServiciosGenerales()

    Public Sub ObtieneInstrumentos()
        Try
            dtInstrumentos.Clear()
            dtInstrumentos = CServiciosMacrosSyBaseDB.ObtieneInstrumentos()
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub ObtienePortafolios()
        Try
            dtPortafolios.Clear()
            dtPortafolios = CServiciosMacrosSyBaseDB.ObtienePortfolios()
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Function ObtieneMaxRenglones() As Integer
        Return Convert.ToInt64(CServicioLocalSQLServerDB.ObtieneMaxRenglones())
    End Function

    Public Function ObtieneRutaTLOADERAPIC() As String
        Return CServicioLocalSQLServerDB.ObtieneRutaTLOADERAPIC()
    End Function

    Public Function ObtieneRutaArchivoAPICPosicion() As String
        Return CServicioLocalSQLServerDB.ObtieneRutaArchivoAPICPosicion()
    End Function

    Public Function ObtieneRutaArchivoAPICEfectivo() As String
        Return CServicioLocalSQLServerDB.ObtieneRutaArchivoAPICEfectivo()
    End Function

    Public Function ObtieneParametrosTLOADERAPIC() As String
        Return CServicioLocalSQLServerDB.ObtieneParametrosTLOADERAPIC()
    End Function

    Public Function InsertaBitacoraDECALOG(ByVal strNombreArchivo As String, ByVal intUsuario As Integer) As Integer
        Try
            Return CServicioLocalSQLServerDB.InsertaBitacoraDECALOG(38, strNombreArchivo, intUsuario)
        Catch ex As Exception

            Return 0
        End Try
    End Function

    Public Function ActualizaBitacoraDECALOG(ByVal intId As Integer, ByVal intEstatus As Integer, ByVal intUsuario As Integer) As Boolean
        Try
            Return CServicioLocalSQLServerDB.ActualizaBitacoraDECALOG(intId, intEstatus, intUsuario)
        Catch ex As Exception
            
            Return False
        End Try
    End Function

    Public Function ActualizaFolioDECALOG(ByVal intId As Integer, ByVal strFolio As String, ByVal intUsuario As Integer) As Boolean
        Try
            Return CServicioLocalSQLServerDB.ActualizaFolioDECALOG(intId, strFolio, intUsuario)
        Catch ex As Exception
            
            Return False
        End Try
    End Function

    Public Function ActualizaMensajeErrorDECALOG(ByVal intId As Integer, ByVal strMensaje As String, ByVal intUsuario As Integer) As Boolean
        Try
            Return CServicioLocalSQLServerDB.ActualizaMensajeErrorDECALOG(intId, strMensaje, intUsuario)
        Catch ex As Exception
            
            Return False
        End Try
    End Function

    Public Sub ValidarOrdenesPos(ByRef Ordenes As ObservableCollection(Of COrdenAPICContingencia), ByRef sMsgError As String)

        Dim inst As String
        Dim inst_num As Integer
        Dim cto As String

        Try
            For Each orden As COrdenAPICContingencia In Ordenes
                orden.RollUpCode = orden.RollUpCode.ToString.Trim.ToUpper
                orden.Serie = orden.Serie.ToString.Trim.ToUpper
                orden.ValueType = orden.ValueType.ToString.Trim.ToUpper
                orden.RefCurveCode = orden.RefCurveCode.ToString.Trim.ToUpper
                orden.IdFuenteInfo = orden.IdFuenteInfo.ToString.Trim.ToUpper
                orden.Mensaje = ""
                If (orden.RollUpCode.Length <= 0 Or orden.RollUpCode.Length > 12) Then
                    orden.Mensaje = "Valor de 'Contrato' incorrecto (Alfanumérico (12))"
                ElseIf (orden.RefCurveCode.Length <= 0 And (orden.Serie.Length <= 0 Or orden.ValueType.Length <= 0)) Then
                    orden.Mensaje = "Debe indicar instrumento en Serie(Emisora_Serie) y ValueType(Tipo Valor) o RefCurveCode(ISIN)"
                Else
                    Try
                        Dim shares = Convert.ToDouble(orden.NumShares.ToString.Replace(",", ""))
                        If shares <= 0 And orden.IdFuenteInfo <> "" Then
                            orden.Mensaje = "Valor de NumShares debe ser un valor mayor a cero cuando es descartado(IdFuenteInfo)"
                        End If
                        If shares = 0 And orden.IdFuenteInfo = "" Then
                            orden.Mensaje = "Valor de NumShares debe ser distinto a cero"
                        End If
                    Catch ex As Exception
                        orden.Mensaje = "Valor de NumShares debe ser un valor numerico"
                    End Try
                End If

                If orden.RollUpCode.Length > 0 And orden.RollUpCode.Length <= 12 Then
                    cto = orden.RollUpCode
                    Dim regs() As DataRow
                    regs = dtPortafolios.Select("PF_COD = '" + cto + "'")
                    If regs.Count = 0 Then
                        orden.Mensaje = "No existe portafolio en Decalog"
                    End If
                End If

                If orden.RefCurveCode.Length > 0 Then
                    inst = orden.RefCurveCode
                    Dim regs() As DataRow
                    regs = dtInstrumentos.Select("INST_ISIN_COD = '" + inst + "'")

                    If regs.Count = 0 Then
                        orden.Mensaje = "No existe instrumento en Decalog"
                    Else
                        orden.InstNum = regs(0)("INST_NUM")
                    End If
                ElseIf orden.Serie.Trim.Length > 0 And orden.ValueType.Trim.Length > 0 Then
                    inst = orden.ValueType + orden.Serie
                    Dim regs() As DataRow
                    regs = dtInstrumentos.Select("INST_SH_NAM_MOD = '" + inst + "'")
                    If regs.Count = 0 Then
                        orden.Mensaje = "No existe instrumento en Decalog"
                    Else
                        orden.InstNum = regs(0)("INST_NUM")
                    End If
                End If

            Next

            Dim result = From ordenesPos In Ordenes
                         Where ordenesPos.InstNum <> 0
                         Group ordenesPos By ordenesPos.RollUpCode, ordenesPos.InstNum Into ordenesgrp = Group
                         Where ordenesgrp.Count > 1

            For Each value In result
                inst_num = value.InstNum
                cto = value.RollUpCode

                Dim ordenesrep = From ordenesPos In Ordenes
                                 Where ordenesPos.RollUpCode = cto And ordenesPos.InstNum = inst_num
                For Each ordenrep As COrdenAPICContingencia In ordenesrep
                    ordenrep.Mensaje = "Registro repetido por portafolio e instrumento"
                Next

            Next

        Catch ex As Exception
            sMsgError = ex.Message
        End Try

    End Sub

    Public Sub ValidarOrdenesEfe(ByRef Ordenes As ObservableCollection(Of COrdenAPICContingencia), ByRef sMsgError As String)

        Dim cto As String
        Try
            For Each orden As COrdenAPICContingencia In Ordenes
                orden.IdFondo = orden.IdFondo.ToString.Trim.ToUpper
                orden.IdFuenteInfo = orden.IdFuenteInfo.ToString.Trim.ToUpper
                orden.Mensaje = ""
                If (orden.IdFondo.Length <= 0 Or orden.IdFondo.Length > 12) Then
                    orden.Mensaje = "Valor de 'Contrato' incorrecto (Alfanumérico (12))"
                Else
                    Try
                        Dim saldo = Convert.ToDouble(orden.Saldo.ToString.Replace(",", ""))
                        If saldo = 0 Then
                            orden.Mensaje = "Valor de Saldo debe ser distinto a cero"
                        End If
                    Catch ex As Exception
                        orden.Mensaje = "Valor de Saldo debe ser un valor numerico"
                    End Try
                End If

                If orden.RollUpCode.Length > 0 And orden.RollUpCode.Length <= 12 Then
                    cto = orden.RollUpCode
                    Dim regs() As DataRow
                    regs = dtPortafolios.Select("PF_COD = '" + cto + "'")
                    If regs.Count = 0 Then
                        orden.Mensaje = "No existe portafolio en Decalog"
                    End If
                End If

            Next

            Dim result = From ordenesEfe In Ordenes
                         Group ordenesEfe By ordenesEfe.IdFondo Into ordenesgrp = Group
                         Where ordenesgrp.Count > 1

            For Each value In result
                cto = value.IdFondo

                Dim ordenesrep = From ordenesEfe In Ordenes
                                 Where ordenesEfe.IdFondo = cto
                For Each ordenrep As COrdenAPICContingencia In ordenesrep
                    ordenrep.Mensaje = "Registro repetido por portafolio"
                Next

            Next

        Catch ex As Exception
            sMsgError = ex.Message
        End Try

    End Sub

    Public Function GeneraArchivo(ByVal strRutaDirectorio As String, ByVal strNombrePrefijo As String, ByRef listOrdenes As ObservableCollection(Of COrdenAPICContingencia), ByVal tipo As String) As String
        Dim strConstructor As StringBuilder = New StringBuilder()
        Dim strNombreFinalArchivo As String
        Dim count As Integer = 1
        Dim fecha As Date = Date.Now
        If tipo = "Pos" Then
            For Each orden As COrdenAPICContingencia In listOrdenes
                strConstructor.Append(count & vbTab & "ENTITE" & vbTab & "ID_XACT" + vbNewLine)
                strConstructor.Append(count & vbTab & "PF_COD" & vbTab & orden.RollUpCode + vbNewLine)
                strConstructor.Append(count & vbTab & "INST_NUM" & vbTab & orden.InstNum.ToString + vbNewLine)
                If orden.IdFuenteInfo = "" Then
                    If orden.NumShares > 0 Then
                        strConstructor.Append(count & vbTab & "XACT_TYP" & vbTab & "CSC" + vbNewLine)
                        strConstructor.Append(count & vbTab & "INST_QTY" & vbTab & orden.NumShares.Replace(",", "") + vbNewLine)
                    Else
                        strConstructor.Append(count & vbTab & "XACT_TYP" & vbTab & "VSC" + vbNewLine)
                        strConstructor.Append(count & vbTab & "INST_QTY" & vbTab & orden.NumShares.Replace(",", "").Replace("-", "") + vbNewLine)
                    End If
                Else
                    If orden.IdFuenteInfo.Contains("DEC") Then
                        strConstructor.Append(count & vbTab & "XACT_TYP" & vbTab & "VSC" + vbNewLine)
                        strConstructor.Append(count & vbTab & "INST_QTY" & vbTab & orden.NumShares.Replace(",", "").Replace("-", "") + vbNewLine)
                    Else
                        strConstructor.Append(count & vbTab & "XACT_TYP" & vbTab & "CSC" + vbNewLine)
                        strConstructor.Append(count & vbTab & "INST_QTY" & vbTab & orden.NumShares.Replace(",", "").Replace("-", "") + vbNewLine)
                    End If
                End If
                strConstructor.Append(count & vbTab & "INST_PRICE" & vbTab & "0" + vbNewLine)
                strConstructor.Append(count & vbTab & "QUOTE_MOD" & vbTab & "P" + vbNewLine)
                strConstructor.Append(count & vbTab & "QTY_EXPR" & vbTab & "Q" + vbNewLine)
                strConstructor.Append(count & vbTab & "CUR_COD" & vbTab & "MXN" + vbNewLine)
                strConstructor.Append(count & vbTab & "BROKER_COD" & vbTab & "FMCBBBVA" + vbNewLine)
                strConstructor.Append(count & vbTab & "COMMENT" & vbTab & "Ajuste de posicion por contingencia (FRIDA)" + vbNewLine)

                count = count + 1
            Next
        End If

        If tipo = "Efe" Then
            For Each orden As COrdenAPICContingencia In listOrdenes
                strConstructor.Append(count & vbTab & "ENTITE" & vbTab & "ID_XACT_CASH" + vbNewLine)
                strConstructor.Append(count & vbTab & "PF_COD" & vbTab & orden.IdFondo + vbNewLine)
                If orden.IdFuenteInfo = "" Then
                    If Convert.ToDouble(orden.Saldo.Replace(",", "")) > 0 Then
                        strConstructor.Append(count & vbTab & "XACTC_TYP" & vbTab & "CASHINJ" + vbNewLine)
                    Else
                        strConstructor.Append(count & vbTab & "XACTC_TYP" & vbTab & "CSHWD" + vbNewLine)
                    End If
                Else
                    If Convert.ToDouble(orden.Saldo.Replace(",", "")) > 0 Then
                        If orden.IdFuenteInfo.Contains("DEC") Then
                            strConstructor.Append(count & vbTab & "XACTC_TYP" & vbTab & "CSHWD" + vbNewLine)
                        Else
                            strConstructor.Append(count & vbTab & "XACTC_TYP" & vbTab & "CASHINJ" + vbNewLine)
                        End If
                    Else
                        If orden.IdFuenteInfo.Contains("DEC") Then
                            strConstructor.Append(count & vbTab & "XACTC_TYP" & vbTab & "CASHINJ" + vbNewLine)
                        Else
                            strConstructor.Append(count & vbTab & "XACTC_TYP" & vbTab & "CSHWD" + vbNewLine)
                        End If
                    End If
                End If
                
                strConstructor.Append(count & vbTab & "AMT_CURRENT" & vbTab & Math.Abs(Convert.ToDouble(orden.Saldo.Replace(",", ""))).ToString("#0.00") + vbNewLine)
                strConstructor.Append(count & vbTab & "CUR_COD" & vbTab & "MXN" + vbNewLine)
                strConstructor.Append(count & vbTab & "COMMENT" & vbTab & "Ajuste de cash por contingencia (FRIDA)" + vbNewLine)
                count = count + 1
            Next
        End If



        strNombreFinalArchivo = strRutaDirectorio + "\" + servGrales.ObtenerPREFIJOARCHIVO + strNombrePrefijo + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".tl"

        Dim swAux As StreamWriter = New StreamWriter(strNombreFinalArchivo)

        swAux.WriteLine(strConstructor)

        swAux.Close()

        Return strNombreFinalArchivo
    End Function

    Public Function ObtieneBitacoraDECALOG(ByVal strFechaInicio As String, ByVal strFechaFin As String) As List(Of CBitacoraDecalog)
        Try
            Dim dtDatos As DataTable = CServicioLocalSQLServerDB.ObtieneBitacoraDECALOG(38, strFechaInicio, strFechaFin)
            Dim lstBitacora As New List(Of CBitacoraDecalog)
            Dim b As CBitacoraDecalog

            If dtDatos.Rows.Count > 0 Then
                For Each dt As DataRow In dtDatos.Rows
                    b = New CBitacoraDecalog()
                    With b
                        .Id = Convert.ToInt32(dt(0))
                        .IdEstatus = Convert.ToInt32(dt(1))
                        .Estatus = Convert.ToString(dt(2))
                        .Archivo = Convert.ToString(dt(3))
                        .Folio = Convert.ToString(dt(4))
                        .Usuario = Convert.ToString(dt(5))
                        .Fecha = Convert.ToDateTime(dt(6))
                        .MensajeError = Convert.ToString(dt(7))
                        .DetalleError = Convert.ToString(dt(8))
                    End With
                    lstBitacora.Add(b)
                    b = Nothing
                Next
            End If

            Return lstBitacora
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Function ActualizaDetalleErrorDECALOG(ByVal intId As Integer, ByVal strMensaje As String, ByVal intUsuario As Integer) As Boolean
        Try
            Return CServicioLocalSQLServerDB.ActualizaDetalleErrorDECALOG(intId, strMensaje, intUsuario)
        Catch ex As Exception
            Dim idRegBit As Integer = CUtileria.GrabarBitacora("APIAssetAllocation", "ActualizaDetalleErrorDECALOG", "Error al actualizar el detalle de error de Decalog: " & intId.ToString & ". Error: " & ex.Message)
            CUtileria.CompletarRegBitacora(idRegBit)

            Return False
        End Try
    End Function

End Class
